package com.roy.ribbon;

import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
/**
 * 自定义ribbo规则
 */
public class MyRule implements IRule {

	private BaseLoadBalancer lb;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public Server choose(Object key) {
		logger.info("进入自定义负载均衡规则");
		
		List<Server> servers = lb.getServerList(true);
		Random ran = new Random(0);
		int index = ran.nextInt(servers.size());
		return servers.get(index);
	}

	public void setLoadBalancer(ILoadBalancer lb) {
		this.lb = (BaseLoadBalancer) lb;
	}

	public ILoadBalancer getLoadBalancer() {
		return this.lb;
	}

}
